package com.simple.api.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * logs 数据库配置
 */
@Configuration
@MapperScan(basePackages = LogsDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "logsSqlSessionFactory")
public class LogsDataSourceConfig {

    // 精确到 master 目录，以便跟其他数据源隔离
    static final String PACKAGE = "com.simple.api.dao.logs";
    static final String MAPPER_LOCATION = "classpath:mapper/logs/*.xml";

    @Bean(name = "logsDataSource")
    @ConfigurationProperties(prefix = "srping.datasource.logs")
    public DataSource logsDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "logsTransactionManager")
    public DataSourceTransactionManager logsTransactionManager() {
        return new DataSourceTransactionManager(logsDataSource());
    }

    @Bean(name = "logsSqlSessionFactory")
    public SqlSessionFactory logsSqlSessionFactory(@Qualifier("logsDataSource") DataSource logsDataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(logsDataSource);
        /*加载mybatis全局配置文件*/
        sessionFactory.setConfigLocation(new PathMatchingResourcePatternResolver().getResource("classpath:mapper/config/sqlMapConfig.xml"));
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(LogsDataSourceConfig.MAPPER_LOCATION));
        return sessionFactory.getObject();
    }




}
